// pages/base/base.js
var app=getApp();
var util=require("../../utils/util")
var base=require("../../api/base");


Page({
  /* 页面的初始数据*/
  data: {
    width: wx.getSystemInfoSync().windowWidth,
    cur_nav: 0,
    nav_list: [],
    nav_id: '',
    base_list: [],
    currentPage: 1,
    pageSize: 10,
    hasMoreData: true,
    show_nav:false
  },
  /* 生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that=this;
    //
    that.get_base_category();
  },
  // 分类切换
  choose_nav:function (e) {
    var that=this,cur_nav=that.data.cur_nav,nav_list=that.data.nav_list,len=nav_list.length;
    var index=e.currentTarget.dataset.index,id=e.currentTarget.dataset.id;
    if(index!=cur_nav){
      that.setData({cur_nav:index,nav_id:id,base_list:[],currentPage:1,show_nav:false })
      // 数据
      that.get_base_list(id)
    }
    if(len >= 3){
      var curWidth = (that.data.width - 30) / 6;
      var moveWidth = (index - 1) * curWidth
      if (moveWidth > 0) {
        that.setData({ scrollLeft: moveWidth })
      } else {
        that.setData({ scrollLeft: 0 })
      }
    }
  },
  // 触底
  onReachBottom:function(){
    var that=this,hasMoreData=that.data.hasMoreData,id=that.data.nav_id;
    if(hasMoreData){
      that.get_base_list(id)
    }else{
      util.page_show_toast('没有更多了',1500)
    }
  },
  // 下拉刷新
  onPullDownRefresh:function(){
    var that=this;
    that.setData({cur_nav:0,nav_list:[],nav_id:'',currentPage:1,hasMoreData: true,base_list:[]});
    // 刷新
    setTimeout(()=>{
      wx.stopPullDownRefresh()
    },500)
    that.get_base_category()
  },
  // 知识库分类
  get_base_category:function(){
    var that=this;
    base.get_base_category().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({nav_list:list,nav_id:list[0].id})
        that.get_base_list(list[0].id)
      }
    })
  },
  // 知识库列表
  get_base_list:function(id){
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize;
    wx.showLoading({title: '加载中'})
    base.get_base_list({
      "currentPage": currentPage,
      "pageSize": pageSize,
      "categoryId": id
    }).then(res=>{
      wx.hideLoading()
      if(res.data.code==200){
        var list = res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].viewCount=list[i].viewCount?(list[i].viewCount>=10000?parseFloat(list[i].viewCount/10000)+"万":list[i].viewCount):0
        }
        var base_list = that.data.base_list;
        base_list = util.extend(base_list, list)
        if (list.length < pageSize) {
          that.setData({
            base_list: base_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            base_list: base_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(list.length==0&&base_list==0){
          that.setData({show_nav:true})
        }
      }
    })
  },
})